<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="600px" @ok="handleSubmit"
    destroyOnClose>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref, useAttrs } from 'vue';
import { BasicForm, useForm } from '/@/components/Form';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { formSchema } from './data';
import { saveOrUpdateLink, getLink } from './api';
import { useMessage } from '/@/hooks/web/useMessage'
const { createMessage } = useMessage();

const emit = defineEmits(['success', 'register']);
const attrs = useAttrs()
const isUpdate = ref(true);
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 90,
  labelCol: {
    md: { span: 4 },
    sm: { span: 6 },
  },
  wrapperCol: {
    md: { span: 20 },
    sm: { span: 18 },
  },
  schemas: formSchema,
  showActionButtonGroup: false
});
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  isUpdate.value = !!data?.isUpdate;
  setDrawerProps({ confirmLoading: false });
  if (unref(isUpdate)) {
    const record = await getLink({ id:  data.record.id, code: data.record.code})
    setFieldsValue({ ...record });
  }
});
/**
 * 标题
 */
const getTitle = computed(() => (!unref(isUpdate) ? '新增短链' : '编辑短链'));
/**
 * 提交
 */
async function handleSubmit() {
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdateLink(values, isUpdate.value);
    closeDrawer();
    emit('success');
    createMessage.success(`${getTitle.value}成功`)
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
